﻿using UnityEngine;
using DG.Tweening;

public static class UIFlyCurve
{
    /// <summary>
    /// UI先上升在沿弧线移动再下降，运动时间随距离变化，弧线部分进行缩放
    /// </summary>
    public static Tweener Fly(
        RectTransform mover,
        Vector2 start,
        Vector2 end,

        float startScale = 0.6f, // 起始缩放（上升和下降阶段保持该值）
        float targetScale = 1f, // 弧线部分的目标缩放
        float arcStartT = 0.25f, // 弧线段开始的 t（0~1）
        float arcEndT = 0.75f, // 弧线段结束的 t（0~1）

        Ease ease = Ease.InQuart,

        float baseDuration = 0.4f, // 基础动画时长（用于很近的情况）
        float durationFactor = 0.002f, // 距离 * 该值，加到时间上
        float riseHeight = 320f, // 起点上升高度（固定）
        float curveHeight = 600f, // 弧线顶点高度（固定）
        float curveRight = 300f // 弧线横向偏移（固定）
    )
    {
        // 距离决定运动时间
        float distance = Vector2.Distance(start, end);
        float duration = baseDuration + distance * durationFactor;

        //弧线的三个点
        Vector2 p1 = start + new Vector2(0, riseHeight);
        Vector2 p2 = (start + end) * 0.5f + new Vector2(curveRight, curveHeight);
        Vector2 p3 = end;

        float t = 0f;

        return DOTween.To(() => t, x =>
            {
                t = x;

                // 贝塞尔曲线固定写法
                Vector2 pos = Mathf.Pow(1 - t, 3) * start +
                              3 * Mathf.Pow(1 - t, 2) * t * p1 +
                              3 * (1 - t) * t * t * p2 +
                              t * t * t * p3;

                mover.anchoredPosition = pos;

                //缩放管理，再弧线部分进行缩放
                if (t <= arcStartT)
                    mover.localScale = Vector3.one * startScale;
                else if (t >= arcEndT)
                    mover.localScale = Vector3.one * targetScale;
                else
                {
                    float u = (t - arcStartT) / (arcEndT - arcStartT); // 0..1
                    float s = Mathf.Lerp(startScale, targetScale, u);
                    mover.localScale = Vector3.one * s;
                }

            }, 1f, duration)
            .SetEase(ease);
    }
}